<script setup lang="ts">
import { ref, watch, watchEffect } from 'vue';

import { ElButton, ElDrawer, ElPagination, ElTable, ElTableColumn, } from 'element-plus';
import { ProSelect } from '@/modules/package/form';
import useTable from '@/hooks/useTable';

import ApiActivity from '@/api/activity';
import ApiMerchant from '@/api/merchant';



const emits = defineEmits<{
    selection: [event: any[]];
}>();

const fetchUrlMap = {
    id: ApiMerchant.merchantList,
    merchant_id: ApiActivity.activityApplyList
};

const mode = ref<keyof typeof fetchUrlMap>("id");
const tableRef = ref();
const selectedMap = new Map();
const fetchUrl = ref(fetchUrlMap.id);

const { isFetching, list, search, pagination, execute, onFetchResponse } = useTable(fetchUrl, {immediate: false});

onFetchResponse(() => {
    setTimeout(() => {
        list.value.forEach((row) => {
            if (selectedMap.get(row[mode.value])) {
                tableRef.value!.toggleRowSelection(row, true);
            }
        });
    }, 500);
});


const setMapItem = (source: any) => {
    const id = source[mode.value];
    selectedMap.set(id, { id, title: source.merchant_title });
};

// 全选/取消全选
const handleSelectionAll = (selection: any[]) => {
    const isSelected = selection.length > 0;
    (isSelected ? selection : list.value).forEach((e) => {
        if (isSelected) {
            setMapItem(e);
        } else {
            selectedMap.delete(e[mode.value]);
        }
    });
};

// 选中/取消某一项
const handleSelection = (selection: any[], row: any) => {
    selection.forEach(setMapItem);
    const flag = selection.includes(row);
    if (!flag) {
        selectedMap.delete(row[mode.value]);
    }
};

watch(() => search.value.act_id, (val) => {
    if (val) execute();
});


watchEffect(() => {
    const { value } = mode;

    if (value == "id") {
        search.value = {};

    } else {
        // 已支付
        search.value = {
            audit_status: 1,
            deposit_status: 1
        };
    }
    fetchUrl.value = fetchUrlMap[mode.value];
    execute();
});


// 确认
const handleConfirmSelection = () => emits("selection", [...selectedMap.values()]);
</script>

<template>
    <ElDrawer size="65%">

        <template #header>
            <div class="flex items-center justify-between">
                <div class="text-lg">选择商家</div>
                <div class="mr-6">
                    <el-radio-group v-model="mode" size="large">
                        <el-radio-button label="直接筛选品牌" value="id" />
                        <el-radio-button label="根据活动报名筛选" value="merchant_id" />
                    </el-radio-group>
                </div>
            </div>
        </template>
        
        <template v-if="mode == 'merchant_id'">
            <ProSelect v-model="search.act_id" placeholder="根据活动标题搜索" :fetchUrl="ApiActivity.activityList"
                       searchKey="act_id"
                       labelKey="title" valueKey="id" />
        </template>

        <ElTable ref="tableRef" :data="list" v-loading="isFetching" @select="handleSelection"
                 @select-all="handleSelectionAll">
            <ElTableColumn type="selection" />
            <ElTableColumn label="品牌名称" prop="merchant_title" />
        </ElTable>

        <template #footer>

            <div class="flex justify-between">
                <ElButton type="primary" @click="handleConfirmSelection">确认</ElButton>
                <ElPagination v-bind="pagination" />
            </div>
        </template>
    </ElDrawer>
</template>